﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Components.Enum;
using UI.Lib;
using UI.Lib.Factory;
using Components;
using Controls;
using Model.Enum;
using System.Collections;
using Com.Seezt.Skins;

namespace UI.ParentForm
{
    public partial class BaseQuery : BaseForm
    {
        /// <summary>
        /// 是否需要加载控件设计
        /// </summary>
        protected bool isNeedControl = true;
        private int gridViewHeadWidth = 0;
        private int showColumnCount = 0; //显示的列的数量
        protected int ShowColumnCount { get { return showColumnCount; } }
        protected string detailDesc = string.Empty;

        //加载完成后是否最大化的标识
        protected bool MaxStateFlag = false;

        public BaseQuery()
        {
            InitializeComponent();
            if (!isDebug)
            {
                PageInit();//初始化方法
                InitControl();// 加载控件设计
                this.dgvDtl.WriteEditCols();
            }
        }

        public BaseQuery(string modulecode, string action)
        {
            if (!string.IsNullOrEmpty(action))
                this.Action = action;

            if (!string.IsNullOrEmpty(modulecode))
                this.ModuleCode = modulecode;

            InitializeComponent();
            PageInit();//初始化方法
            InitControl();// 加载控件设计
            this.dgvDtl.WriteEditCols();
        }

        /// <summary>
        /// 加载控件设计
        /// </summary>
        private void InitControl()
        {
            if (!isNeedControl) //不加载数据库的字段设计
            {
                this.tbSummary.Visible = false;
                return;
            }

            string page = this.GetType().FullName;

            //加载页面概要设计信息
            CommonObject obj = PageCache.GetSys5A00(page, PageControlType.SummaryCtl);
            if (obj.IsEmptyData) return; //页面未设置概要信息

            int colsize = Convert.ToInt32(obj.GetValue("colsize"));
            string text = Validation.ToString(obj.GetValue("remark"));

            //加载页面控件数据设计
            Dictionary<string, DataTable> ctls = PageCache.GetLayouts(page,
                                            PageControlType.SummaryCtl,
                                            PageControlType.DetailCtl
                                        );

            if (ctls == null)
                return;

            DataTable dt = ctls[PageControlType.SummaryCtl]; //加载页面控件数据设计
            DataTable dtDtl = ctls[PageControlType.DetailCtl]; //查询明细列的设计情况

            if (null == dt || 0 == dt.Rows.Count) return;

            //加载概要
            tbSummary.DataSource = dt;
            tbSummary.AutoHeight = true;
            tbSummary.ColSize = colsize;
            tbSummary.Bind();

            List<object> lstdefaults = new List<object>();
            //加载明细列设计
            PsDataGridViewTextBoxColumn col = null;
            List<string> dtlpop = null;
            string tp3;
            int temp = 0;
            DataGridViewCellStyle cs1 = null;
            foreach (DataRow dr in dtDtl.Rows)
            {
                col = new PsDataGridViewTextBoxColumn();
                col.Name = dr["colname"].ToString();
                tp3 = Validation.ToString(dr["tp3"]);
                col.DataPropertyName = col.Name;
                col.ColType = (PsDataType)Convert.ToInt32(dr["coltype"]);
                col.HeaderText = dr["headcn"].ToString();
                col.Visible = ("n" == dr["isshow"].ToString().ToLower()); //数据库中isshow y和n刚好搞反了
                temp = Validation.ToInt(dr["columnwidth"]);
                col.Width = col.DefaultWidth = col.Visible ? 
                    ((0 == temp) ? GridViewUtil.Entity.GetHeadWidth(col.HeaderText) :  temp) : 0;

                string format = Validation.ToString(dr["fmt"]);
                if (string.IsNullOrEmpty(format)
                    && (col.ColType == PsDataType.Date || col.ColType == PsDataType.Date))
                {
                    format = "yyyy-MM-dd";
                }

                if (Global.IsNumType(col.ColType))
                    col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

                if (!string.IsNullOrEmpty(format))
                    col.DefaultCellStyle.Format = format;

                if (!string.IsNullOrEmpty(tp3)) //tp3用来存储某字段的显示条件
                {
                    col.Visible = tp3.IndexOf(this.Action) > -1;
                }

                gridViewHeadWidth += col.Width;

                lstdefaults.Add(col.DefaultValue); //设置默认值

                if (col.Visible) showColumnCount++;

                if (!string.IsNullOrEmpty(col.PopKey)) //只要设置了PopKey则说明是弹出框
                {
                    if (null == dtlpop)
                    {
                        dtlpop = new List<string>();
                    }

                    dtlpop.Add(col.Name);
                }

                col.ReadOnly = col.EditMode.IndexOf(this.Action) == -1;

                this.dgvDtl.Columns.Add(col);
            }

            this.dgvDtl.AutoGenerateColumns = false;

            AfterLoadControl();
        }

        /// <summary>
        /// 创建完控件后执行（添加属性）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void tbSummary_AfterCreateControl(object sender, Controls.Args.SummaryArgs e)
        {
            Control c = sender as Control;
            if (c == null) return;

            //添加默认事件
            AddEvent(c);

            AfterCreateSummaryControl(c.Name, c);
        }

        protected virtual void AfterCreateSummaryControl(string name, Control c) { }

        protected override void AfterSummaryPopUp(PsPopWin popTarget, Hashtable hs, bool clearFlag, string status)
        {
            if (null == hs || 0 == hs.Count) return;

            Control c = null;
            PsPopWin pop = null;
            string key = "";
            string value = "";
            bool isAlert = false;
            foreach (DictionaryEntry entry in hs)
            {
                key = entry.Key.ToString();
                value = (null == entry.Value || clearFlag) ? "" : entry.Value.ToString();
                if (key == "$SELF$")
                {
                    popTarget.Text = popTarget.Value = value;
                    if (!string.IsNullOrEmpty(value))
                    {
                        popTarget.PressWord = null;
                    }
                    if (!clearFlag && string.IsNullOrEmpty(value))
                    {
                        isAlert = true; //给出提示
                    }
                }
                else if (key.IndexOf("$VALUE$") > -1)//准备将值写入弹出框份额Value内
                {
                    if (key.IndexOf("&") > -1)//准备将值写入其他弹出框份额Value内
                    {
                        string name = key.Replace("$VALUE$&", "");
                        if (!this.tbSummary.Controls.ContainsKey(name)) continue;

                        pop = this.tbSummary.Controls[name] as PsPopWin;
                        if (pop == c) continue;

                        pop.Value = value;
                    }
                    else
                    {
                        popTarget.Value = value;
                    }
                }
                else
                {
                    this.tbSummary.SetValue(key, value);
                }
            }

            if (isAlert && "M" != status)
            {
                popwin_MouseDoubleClick(popTarget, null);
                // MessageBox.Show(string.Format("[{0}]未选择有效的值！", popTarget.Lable), "提示");
            }
        }

        #region 抽象的虚方法

        //初始化方法
        protected virtual void PageInit() { }

        /// <summary>
        /// Medit页面生成完控件执行
        /// </summary>
        protected virtual void AfterLoadControl() { }

        #endregion


        /// <summary>
        /// 充值GridView的宽度
        /// </summary>
        void ResetColumnWidth()
        {
            if (this.dgvDtl.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.None)
            {
                foreach (PsDataGridViewTextBoxColumn dc in this.dgvDtl.Columns)
                {
                    dc.Width = dc.DefaultWidth;
                }
            }
        }

        protected void BaseMain_ClientSizeChanged(object sender, EventArgs e)
        {
            AutoSize();

            //如果单元格的宽度之和小于我的GridView的宽度，则自动填充满
            this.dgvDtl.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;

            ResetColumnWidth();
        }

        protected void BaseMain_Shown(object sender, EventArgs e)
        {
            BaseMain_ClientSizeChanged(sender, e);
        }

        protected virtual void AutoSize() { }

        /// <summary>
        /// 根据概要的高度，重置明细的高度
        /// </summary>
        protected void ResetSize()
        {
            int clientWidth = this.ClientSize.Width;

            int summaryHeight = this.tbSummary.Height;
            summaryHeight = Math.Max(summaryHeight, 50);
            this.tbSummary.Size = new Size(clientWidth - 40, summaryHeight);
            int winHeight = this.Height;
            int spaceHeight = 10; //概要明细中的高度

            this.panToolBar.Location = new Point(this.tbSummary.Location.X, this.tbSummary.Location.Y + this.tbSummary.Height + 3);
            this.panToolBar.Size = new Size(this.tbSummary.Width, 28);

            this.panDtl.Location = new Point(this.tbSummary.Location.X, spaceHeight + summaryHeight + 70);
            this.panDtl.Size = new Size(this.tbSummary.Width, winHeight - summaryHeight - spaceHeight - 110);
        }

        /// <summary>
        /// 根据当前状态，充值页面控件状态
        /// </summary>
        protected void RefreshControl()
        {
            this.tbSummary.SetControlState(this.Action);
        }

        /// <summary>
        /// 当页面上系统设置完控件状态后执行
        /// </summary>
        protected virtual void AfterSystemChangeControlState() { }


        /// <summary>
        /// 页面加载完成后，自动重置一次控件状态
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (MaxStateFlag)
            {
                this.WindowState = FormWindowState.Maximized;
            }

            this.RefreshControl();
            AfterSystemChangeControlState();
            this.ResetSize();
            this.tbSummary.FormatStyle();
            this.ResetSize(); //由于在FormatStyle中我重新设置了概要的高度，所以需要重新计算Location
            _SetFontSize();
            this.lbDesc.Text = detailDesc;
            isLoadOk = true;
        }

        void _SetFontSize()
        {
            this.AutoScaleMode = AutoScaleMode.None;

            this.tbSummary.Font
                = this.dgvDtl.Font = Global.AllFont;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            _doSearch();
        }

        private void _doSearch()
        {
            if (!AutoCheck()) return;

            DoSearch();
        }

        protected virtual void DoSearch() { }

        protected bool AutoCheck()
        {
            string errmsg = this.tbSummary.CheckSelf();
            bool rlt = string.IsNullOrEmpty(errmsg);
            if (rlt == false)
            {
                MsgBox.ShowErrorMsg(this, errmsg);
                return false;
            }

            return true;
        }

        private void BaseQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F8)
            {
                _doSearch();
            }
            else if (e.KeyCode == Keys.F9)
            {
                _doExport();
            }
        }

        protected void BinderGrid(DataTable data)
        {
            this.dgvDtl.DataSource = null;

            if (null == data || 0 == data.Rows.Count)
            {
                MsgBox.Show(this, "未能查询到任何数据，请调整查询条件！");
                return;
            }

            this.dgvDtl.DataSource = data;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            _doExport();
        }

        protected void SetDetailDesc(string desc)
        {
            this.detailDesc = desc;

            this.lbDesc.Text = this.detailDesc;
        }

        private void _doExport()
        {
            if (0 == dgvDtl.Rows.Count)
            {
                MsgBox.Show(this, "没有可供导出的数据！");
                return;
            }

            ExportExcel.DataGridViewToExcel(this.dgvDtl);
        }

        private void dgvDtl_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;

            OnRowDoubleClick(this.dgvDtl.Columns[e.ColumnIndex].Name, e.RowIndex);
        }

        protected virtual void OnRowDoubleClick(string colName, int rowIndex) { }
    }
}
